package com.action.gulimall.product.service.impl;

import com.action.gulimall.product.service.CategoryBrandRelationService;
import com.action.gulimall.product.vo.Catelog2Vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.action.gulimall.product.dao.CategoryDao;
import com.action.gulimall.product.entity.CategoryEntity;
import com.action.gulimall.product.service.CategoryService;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> findListTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> levelMenu = entities.stream()
                .filter(menu -> menu.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted(CategoryEntity::sortBySort)
                .collect(Collectors.toList());
        return levelMenu;
    }

    @Override
    public void removeMenuByIds(List<Long> longs) {
        //TODO 1.检查是否有其他地方引用到，不然不能随便删除
        baseMapper.deleteBatchIds(longs);
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> catelogPaths = new ArrayList<Long>();
        catelogPaths.add(catelogId);
        findParentCatelogPath(catelogPaths,catelogId);
        Collections.reverse(catelogPaths);
        log.debug(catelogPaths.toString());
        return catelogPaths.toArray(new Long[catelogPaths.size()]);
    }

    @CacheEvict(value = "category",allEntries = true)
//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category",key = "'getCatalogJson'")
//    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys(){
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    public List<CategoryEntity> getLevel1CategorysRedisCache(){
        //System.out.println("getLevel1Categorys........");
        //long l = System.currentTimeMillis();
        String level1Categorys = redisTemplate.opsForValue().get("level1Categorys");
        //System.out.println("level1Categorys.size="+level1Categorys.getBytes().length);
        if(!StringUtils.isEmpty(level1Categorys)){
            return JSON.parseObject(level1Categorys, new TypeReference<List<CategoryEntity>>(){});
        }else{
            String keyValue=UUID.randomUUID()+""+System.nanoTime();
            //原子获取锁
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("level1CategorysKey", keyValue, 10, TimeUnit.SECONDS);
            if(lock){
                List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
                redisTemplate.opsForValue().set("level1Categorys", JSON.toJSONString(categoryEntities));
                //原子释放锁
                redisTemplate.execute(new DefaultRedisScript<Long>(
                        "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                                "    return redis.call(\"del\",KEYS[1])\n" +
                                "else\n" +
                                "    return 0\n" +
                                "end",Long.class), Arrays.asList("level1CategorysKey"),keyValue);
                return categoryEntities;
            }else{
                try{
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getLevel1Categorys();
            }
        }

    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        return getStringListMap();
    }

    @Autowired
    RedissonClient redissonClient;

    public Map<String, List<Catelog2Vo>> getCatalogJsonRedissonLock(){
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(!StringUtils.isEmpty(catalogJson)){
            return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }else{
            RLock rLock = redissonClient.getLock("catalogJsonKey");
            try{
                rLock.lock(2, TimeUnit.SECONDS);
                Map<String, List<Catelog2Vo>> stringListMap = getStringListMap();
                redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(stringListMap));
                return stringListMap;
            }catch (Exception e) {
                throw e;
            }finally {
                rLock.unlock();
            }
        }
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonRedisLock() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(!StringUtils.isEmpty(catalogJson)){
            return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }else{
            String keyValue=UUID.randomUUID()+""+System.nanoTime();
            //原子获取锁
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("catalogJsonKey", keyValue, 10, TimeUnit.SECONDS);
            if(lock){
                Map<String, List<Catelog2Vo>> stringListMap = getStringListMap();
                redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(stringListMap));
                //原子释放锁
                redisTemplate.execute(new DefaultRedisScript<Long>(
                        "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end",Long.class), Arrays.asList("catalogJsonKey"),keyValue);
                return stringListMap;
            }else{
                try{
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCatalogJson();
            }
        }
    }



    private Map<String, List<Catelog2Vo>> getStringListMap() {
        List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(null);
        //查询第一层
        List<Long> level_1_ids = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> categoryEntity.getCatId())
                .collect(Collectors.toList());
        //封装第二层和第三层
        Map<String, List<Catelog2Vo>> listMap = level_1_ids.stream().collect(Collectors.toMap(k -> k.toString(), v -> {
            List<Catelog2Vo> catelog2Vos = findLevel2ByCatId(v, categoryEntityList);
            catelog2Vos.stream().map(catelog2Vo -> {
                List<Catelog2Vo.Category3Vo> category3Vos = findLevel3ByCatId(Long.valueOf(catelog2Vo.getId()), categoryEntityList);
                catelog2Vo.setCatalog3List(category3Vos);
                return catelog2Vo;
            }).collect(Collectors.toList());
            return catelog2Vos;
        }));
        return listMap;
    }

    public List<Catelog2Vo> findLevel2ByCatId(Long catId,List<CategoryEntity> categoryEntityList){
        List<Catelog2Vo> catelog2VoList = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == catId)
                .map(categoryEntity -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setId(categoryEntity.getCatId().toString());
                    catelog2Vo.setName(categoryEntity.getName());
                    catelog2Vo.setCatalog1Id(catId.toString());
                    return catelog2Vo;
                })
                .collect(Collectors.toList());
        return catelog2VoList;
    }

    public List<Catelog2Vo.Category3Vo> findLevel3ByCatId(Long catId, List<CategoryEntity> categoryEntityList){
        List<Catelog2Vo.Category3Vo> catelog3VoList = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == catId)
                .map(categoryEntity -> {
                    Catelog2Vo.Category3Vo catelog3Vo = new Catelog2Vo.Category3Vo();
                    catelog3Vo.setId(categoryEntity.getCatId().toString());
                    catelog3Vo.setName(categoryEntity.getName());
                    catelog3Vo.setCatalog2Id(catId.toString());
                    return catelog3Vo;
                })
                .collect(Collectors.toList());
        return catelog3VoList;
    }

    public void findParentCatelogPath(List<Long> catelogPaths,Long catelogId){
        if(catelogId==0){
            //log.debug("find catelogPaths="+catelogId+" parentId");
            return;
        }
        log.debug("find catelogId="+catelogId+" parentId");
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if(categoryEntity!=null&&categoryEntity.getParentCid()>0){
            catelogPaths.add(categoryEntity.getParentCid());
            findParentCatelogPath(catelogPaths,categoryEntity.getParentCid());
        }
        //return catelogPaths.toArray(new Long[catelogPaths.size()]);
    }

    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> entities = all.stream()
                .filter(entity -> entity.getParentCid() == root.getCatId())
                .map((entity) -> {
                    entity.setChildren(getChildren(entity, all));
                    return entity;
                })
                .sorted(CategoryEntity::sortBySort)
                .collect(Collectors.toList());
        return entities;
    }


}